package com.younion.action.manage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.younion.business.ICustomerService;
import com.younion.business.IFavourableEntityService;
import com.younion.business.IFavourableService;
import com.younion.business.IMemberCardService;
import com.younion.common.base.BaseAction;
import com.younion.common.paginator.Paginator;
import com.younion.util.UUIDUtil;
import com.younion.vo.CustomerVO;
import com.younion.vo.FavourableEntityVO;
import com.younion.vo.FavourableVO;
import com.younion.vo.MemberCardVO;

import cpcns.jhsks.util.MapCollectionUtils;


/**
 * @author jillchan
*/
public class FavourableAction extends BaseAction {

	protected static final Log logger = LogFactory.getLog(FavourableAction.class);
	private IFavourableService favourableService = null;
	
	private IFavourableEntityService favourableEntityService = null;
	
	private IMemberCardService memberCardService = null;
	
	private ICustomerService customerService = null;
	
	private FavourableVO favourableVO = new FavourableVO();

	private List<FavourableVO> favourableList; 
	
	private List<FavourableEntityVO> favourableEntityList; 
	
	private UUIDUtil uUIDUtil = new UUIDUtil(); 
	
	/**
	 *  列表：翻页区；数据区
	 */
	@RequiresPermissions("listFavourable")
	public String listFavourable() {
		try {
			Map paramMap = null;
			CustomerVO customer = getSessionUser().getCustomer();
			Integer userCustomerId = null;
			if(customer != null){
				userCustomerId = customer.getId();
			}
			if (favourableVO != null) {
				if(userCustomerId != null && favourableVO.getCustomerId() == null){
					//if customer user login
					favourableVO.setCustomerId(userCustomerId);
				}
				paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(favourableVO));
			}
			// 获取总记录数 
			int total = favourableService.getCountByMap(paramMap);
			// 根据总记录数获取分页对象 
			Paginator paginator = this.getPaginator(total);
			
			favourableList = favourableService.get(paramMap, paginator);
			// 保存分页对象
			this.savaPaginator(paginator);
			this.addLog(2, "查询优惠券实例列表", "查询优惠券实例列表", this.getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}

	/**
	 *  新增
	 */
	@RequiresPermissions("addFavourable")
	public String addFavourable() {
		try{
		Map resultMap = this.inintParamMap();
		String keys = (String) resultMap.get("keys");
		
		if(keys != null){
		List cardIdList = Arrays.asList(keys.split(","));
		//如果只选择了一个会员卡则根据此会员卡所属商户选择优惠券实体
		if(cardIdList != null && cardIdList.size() == 1){
		MemberCardVO memberCard = memberCardService.getById(keys);
		resultMap.put("customerId", memberCard.getCustomerId());
		}
		}
		//如果paramMap不包含customerId，即超级用户，使用customerName获得customerId
		if(!resultMap.containsKey("customerId")){
		Map customerParamMap =new HashMap();
		String customerName = (String) resultMap.get("customerName");
		customerParamMap.put("name", customerName);
		CustomerVO customer = (CustomerVO) ((List)customerService.getByMap(customerParamMap)).get(0);
		resultMap.put("customerId",customer.getId() );
		}
		
		request.setAttribute("resultMap", resultMap);
		}catch(Exception e){
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 *  修改保存，调度Jsp
	 */
	@RequiresPermissions("editFavourable")
	public String editFavourable() {
		try {
			favourableVO = favourableService.getById(favourableVO.getId().toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 *  发放优惠券
	 */
	@RequiresPermissions("releaseFavourable")
	public String releaseFavourable() {
		try {	
			    String customerId = request.getParameter("customerId");
			    String favourableEntityid = request.getParameter("favourable.favourableEntityId");
				FavourableEntityVO favourableEntityVO =favourableEntityService.getById(favourableEntityid);
				int releaseNum = Integer.parseInt(request.getParameter("releaseNum"));
				List<FavourableVO> favourables = new ArrayList<FavourableVO>();
				String releaseType = request.getParameter("releaseType");
				Map updateCouponParam = new HashMap();
				updateCouponParam.put("customerId", customerId);
				List userIds = new ArrayList(); 
			//选择发送
			if("sel".equals(releaseType)){
			    String pkId = request.getParameter("keys");
				List cardIdList = Arrays.asList(pkId.split(","));
				if (cardIdList != null ) {
					Iterator it = cardIdList.iterator();
					while(it.hasNext()) {
						String cardId = (String)it.next();
						MemberCardVO memberCardVO = memberCardService
								.getById(cardId);
						for(int i = 0;i<releaseNum;i++){
							FavourableVO favourable = new FavourableVO();
							favourable.setCustomerId(Integer.valueOf(customerId));
							favourable.setMemberCard(memberCardVO.getId());
							favourable.setFavourableEntity(favourableEntityVO);
							favourable.setCode(uUIDUtil.getUuid().toString());
							favourable.setState(0);
							favourable.setGainManner(0);
							favourable.setGainTime(new Date());
							Integer userId = memberCardVO.getUserId();
							favourable.setUserId(userId);
							favourables.add(favourable);
							if(!userIds.contains(userId)){
								//若列表中不包含则添加
								userIds.add(userId);
							}
						}
					}
//					addCouponParam.put("ids", cardIdList);
				}
			//全部发送	
			}else if("all".equals(releaseType)){
				Map resultMap = inintParamMap();
				resultMap.remove("customerName");
				List<MemberCardVO> memberCardList = (List) memberCardService.getByMap(resultMap);
				List cardIdList = new ArrayList();
				for(MemberCardVO membercard : memberCardList){
					for(int i = 0;i<releaseNum;i++){
							FavourableVO favourable = new FavourableVO();
							favourable.setCustomerId(Integer.valueOf(customerId));
							favourable.setMemberCard(membercard.getId());
							favourable.setFavourableEntity(favourableEntityVO);
							String code = uUIDUtil.getUuid().toString();
							favourable.setCode(code);
							favourable.setState(0);
							favourable.setGainManner(0);
							favourable.setGainTime(new Date());
							Integer userId = membercard.getUserId();
							favourable.setUserId(userId);
							favourables.add(favourable);
							if(!userIds.contains(userId)){
								//若列表中不包含则添加
								userIds.add(userId);
							}
					}
//					cardIdList.add(membercard.getId());
				}
//				addCouponParam.put("ids", cardIdList);
			//随机发送		
			}else if("ram".equals(releaseType)){
				Map resultMap = inintParamMap();
				resultMap.remove("customerName");
				List<MemberCardVO> memberCardList = (List) memberCardService.getByMap(resultMap);
				//打乱memberCardList顺序
				Collections.shuffle(memberCardList);
				int ramCardNum = Integer.parseInt((String)(resultMap.get("ramCardNum")));
				List cardIdList = new ArrayList();
				for(int i = 0;i<ramCardNum;i++){
					MemberCardVO membercard = memberCardList.get(i);
					for(int j = 0;j<releaseNum;j++){
					FavourableVO favourable = new FavourableVO();
					favourable.setCustomerId(Integer.valueOf(customerId));
					favourable.setMemberCard(membercard.getId());
					favourable.setFavourableEntity(favourableEntityVO);
					String code = uUIDUtil.getUuid().toString();
					favourable.setCode(code);
					favourable.setState(0);
					favourable.setGainManner(0);
					favourable.setGainTime(new Date());
					Integer userId = membercard.getUserId();
					favourable.setUserId(userId);
					favourables.add(favourable);
					if(!userIds.contains(userId)){
						//若列表中不包含则添加
						userIds.add(userId);
					}
					}
				}
			}
			if(favourables.size() > 0){
			favourableService.insertVos(favourables);
			updateCouponParam.put("userIds", userIds);
			memberCardService.updateCouponAmounts(updateCouponParam);
			}
			request.setAttribute("refreshNavTabId", "favourableList");
			this.addLog(3, "发放优惠券", "发放优惠券", this.getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 保存及使用优惠券
	 * @return
	 */
	@RequiresPermissions("saveFavourable")
	public String saveFavourable() {
		try {
			String act = request.getParameter("act");
			if (act != null && "use".equals(act)) {
				String pkId = request.getParameter("ids");
				List<String> idList = Arrays.asList(pkId.split(","));
				Map map = new HashMap();
				favourableService.modifyFavourablesState(idList);
				for(String favId : idList){
					FavourableVO favourable = favourableService.getById(favId);
					map.put("userId", favourable.getUserId());
					map.put("customerId", favourable.getCustomerId());
					//更新会员卡优惠券数量
					memberCardService.updateCouponAmount(map);
					map.clear();
				}
				
				
			} else {
				favourableVO = favourableService.save(favourableVO);
			}
			request.setAttribute("refreshNavTabId", "favourableList");
			String id = favourableVO.getId() == null ? "" : favourableVO.getId().toString();
			String log = "".equals(id) ? "添加优惠券实例" : "更新优惠券实例";
			int type = "".equals(id) ? 3:4;
			this.addLog(type, log+id, log,getSessionUser());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 *  删除
	 */
	@RequiresPermissions("deleteFavourable")
	public String deleteFavourable() {
		try {
			String pkId = request.getParameter("ids");
			favourableService.remove(Arrays.asList(pkId.split(",")));
			request.setAttribute("refreshNavTabId", "favourableList");
			String log = "删除优惠券实例";
			this.addLog(5, log+pkId, log,getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	/**
	 *  查看
	 */
	@RequiresPermissions("viewFavourable")
	public String viewFavourable() {
		try {
			favourableVO = favourableService.getById(favourableVO.getId().toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;

	}
	/**
	 * 转换request.parameterMap
	 */
	private HashMap inintParamMap() throws Exception{
		Map map = request.getParameterMap();
		Set set = map.keySet();
		Iterator it = set.iterator();
		HashMap resultMap = new HashMap();
		while(it.hasNext()){
			String key = (String) it.next();
			String value = ((String[])map.get(key))[0];
			value = java.net.URLDecoder.decode(value,"utf-8");
//			System.out.println("key1="+key+" : value1="+value);
			resultMap.put(key, value);
		}
		return resultMap;
	}
	public FavourableVO getFavourableVO() {
		return favourableVO;
	}

	public void setFavourableVO(FavourableVO favourableVO) {
		this.favourableVO = favourableVO;
	}

	public void setFavourableService(IFavourableService favourableService) {
		this.favourableService = favourableService;
	}

	public List<FavourableVO> getFavourableList() {
		return favourableList;
	}

	public void setFavourableList(List<FavourableVO> favourableList) {
		this.favourableList = favourableList;
	}

	public List<FavourableEntityVO> getFavourableEntityList() {
		return favourableEntityList;
	}

	public void setFavourableEntityList(
			List<FavourableEntityVO> favourableEntityList) {
		this.favourableEntityList = favourableEntityList;
	}

	public void setFavourableEntityService(
			IFavourableEntityService favourableEntityService) {
		this.favourableEntityService = favourableEntityService;
	}

	public void setMemberCardService(IMemberCardService memberCardService) {
		this.memberCardService = memberCardService;
	}

	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	
	

}